package com.acme.bankapp.network;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import com.acme.bankapp.domain.bank.Bank;

public class BankServer {
    ServerSocket providerSocket;
    Socket connection = null;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;
    BankReport bankReport;

    public BankServer() {
    }

    private void run() {
	try {
	    providerSocket = new ServerSocket(2004, 10);
	    System.out.println("Waiting for connection");
	    connection = providerSocket.accept();
	    System.out.println("Connection received from "
		    + connection.getInetAddress().getHostName());
	    out = new ObjectOutputStream(connection.getOutputStream());
	    out.flush();
	    in = new ObjectInputStream(connection.getInputStream());
	    sendMessage("Connection successful");
	    do {
		try {
		    message = (String) in.readObject();
		    System.out.println("client>" + message);
		    if (message.equals("bye"))
			sendMessage("bye");
		    Command command = bankReport.processInput(message);
		    sendMessage(command.execute());
		} catch (ClassNotFoundException classnot) {
		    System.err.println("Data received in unknown format");
		}
	    } while (!message.equals("bye"));
	} catch (IOException ioException) {
	    ioException.printStackTrace();
	} finally {
	    try {
		in.close();
		out.close();
		providerSocket.close();
	    } catch (IOException ioException) {
		ioException.printStackTrace();
	    }
	}
    }

    private void sendMessage(final String msg) {
	try {
	    out.writeObject(msg);
	    out.flush();
	    System.out.println("server>" + msg);
	} catch (IOException ioException) {
	    ioException.printStackTrace();
	}
    }

    public void startServer(final Bank bank) {
	bankReport = new BankReport(bank);
	while (true) {
	    run();
	}
    }
    
}
